package org.fhawk.tinyspring.mvc;

import org.fhawk.tinyspring.mvc.bean.Handler;
import org.fhawk.tinyspring.mvc.bean.Requester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by tuo on 9/5/2016.
 */
@WebServlet(urlPatterns = "/*")
public class ServletAll extends HttpServlet {
    private final Logger logger = LoggerFactory.getLogger(ServletAll.class);


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI();
        path = path.contains(".") ? path.substring(0, path.indexOf('.')) : path;
        String method = req.getMethod();
        Requester requester = new Requester(method, path);
        Handler handler = ActionHelper.handler(requester);
        if (handler == null) {
            resp.sendError(404, "not found");
        } else {
            try {
                HandlerHelper.invoke(req, resp, handler);
            } catch (Exception e) {
                logger.error("调用方法失败。", e);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        }

    }
}
